package com.licg.chatroom.servlet;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringEscapeUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.licg.chatroom.bean.MessageBean;
import com.licg.chatroom.bean.MessageListBean;

/**
 * Servlet implementation class ChatServlet
 */
public class ChatServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}
	
	private void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String uri=request.getRequestURI();
		int doend=uri.indexOf(".do");
		int dostart=uri.lastIndexOf("/",doend)+1;
		String type=uri.substring(dostart, doend);
		if(type!=null){
			if(type.equals("login")){
				login(request, response);
			}else if(type.equals("logout")){
				logout(request, response);
			}else if(type.equals("receviceMessage")){
				receviceMessage(request, response);
			}else if(type.equals("sendMessage")){
				sendMessage(request, response);
			}else if(type.equals("getUsers")){
				getUsers(request, response);
			}else if(type.equals("getUserInfo")){
				getUserInfo(request, response);
			}
		}
	}
	
	/**
	 * 获取当前用户信息
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void getUserInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session=request.getSession();
		String username=(String) session.getAttribute("username");
		System.out.println("用户："+username+"信息获取");
		if(username==null){
		  //将用户未登录的信息返回给页面
		   response.getWriter().write("{\"error\":\"nouser\"}");
		}else{
			 response.getWriter().write("{\"username\":\""+username+"\"}");
		}
	}
	
	/**
	 * 登录
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//用户登陆
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		System.out.println(username);
		System.out.println(password);
		HttpSession session=request.getSession();
		session.setAttribute("username", username);
		
		// 将用户名信息放到map中//用户接收的到的消息bean
		Map<String,List<MessageBean>> rMap=new ConcurrentHashMap<String,List<MessageBean>>();
		ChatServlet.allUserRMap.put(username, rMap);
		//如果用户还未登录，记录到list中
		if (!ChatServlet.allUserList.contains(username)) {
			ChatServlet.allUserList.add(username);
		}
		response.getWriter().write("success");
	}
	/**
	 * 注销
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session=request.getSession();
		String username=(String) session.getAttribute("username");
		System.out.println("用户："+username+"注销");
		session.removeAttribute("username");	
		ChatServlet.allUserRMap.remove(username);
//		ChatServlet.allUserVMap.remove(event.getValue());
		//如果用户已经登录，从list中删除
		if (ChatServlet.allUserList.contains(username)) {
			ChatServlet.allUserList.remove(username);
		}
		session.invalidate();	
		response.getWriter().write("success");
		
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void getUsers(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获得所有用户信息
		JSONArray allUserListJson = JSONArray.fromObject(allUserList);
//		System.out.println(allUserListJson.toString());
		response.getWriter().write(allUserListJson.toString());
	}
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void receviceMessage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//获得当前用户
		String nowUserName=(String) request.getSession().getAttribute("username");

		//从map中获得当前用户接收到的消息的MAP
		Map<String,List<MessageBean>> messageMap=allUserRMap.get(nowUserName);
//		//已经看到的消息
//		List<MessageBean> vList=allUserVMap.get(nowUserName);
		//将未看到的消息显示到页面上
		MessageListBean messageListBean=new MessageListBean();
		messageListBean.setMessageMap(messageMap);
		//将消息转换为json对象
		JSONObject messageBeanJson = JSONObject.fromObject(messageListBean);
		String jsonString=messageBeanJson.toString();
		//上一步添加完成后然后将未看到的消息清空
		Set<Entry<String, List<MessageBean>>> messageEntrySet = messageMap.entrySet();
		for(Entry<String, List<MessageBean>> entry:messageEntrySet){
			entry.getValue().clear();
		}
//		System.out.println(jsonString);
		//将json对象发布到页面进行显示
		response.getWriter().write(jsonString);
	}
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void sendMessage(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		//用户发布的消息
		String message=request.getParameter("message");
//		System.out.println(message);
		//用户想发送消息到 的用户
		String toUserName=request.getParameter("toUserName");
		//具体消息bean
		MessageBean messageBean = new MessageBean();
		messageBean.setTime("时间:"+getNowStringDate());
		messageBean.setMessage("信息:"+htmlChangeWithBR(message));
		//消息作者
		String authorName=(String) request.getSession().getAttribute("username");
		//获得发送到的用户的Map
		Map<String,List<MessageBean>> rMap=allUserRMap.get(toUserName);
		//说明这个接收消息的用户是登陆状态
		if(rMap!=null){			
			List<MessageBean> rList = rMap.get(authorName);	
			//如果还未创建消息列表则创建
			if(rList==null){
				rList=new CopyOnWriteArrayList<MessageBean>();
			}
			rList.add(messageBean);
			rMap.put(authorName, rList);
		}else{
			//如果对方未登陆
			//将用户未登录的信息返回给页面
			response.getWriter().write("{\"error\":\"nouser\"}");
			return;
		}
//		//将自己发布的消息放到已经看到过的消息列表
//		List<MessageBean> vList=allUserVMap.get(toUserName);	
//		vList.add(messageBean);
		//将消息 bean转换为json对象 
		JSONObject messageBeanJson = JSONObject.fromObject(messageBean);
		//json对象发布到页面显示
		response.getWriter().write(messageBeanJson.toString());

	}
	
	/**
	 * 存储所有用户   ---------------用户名称列表
	 */
	public static final List<String> allUserList=new CopyOnWriteArrayList<String>();	
	
	/**
	 *存储所有用户   ---------------收到的还未看到的过的消息
	 *map(用户名，用户消息Map（发送消息者，接收到的消息list）);
	 */
	public static final Map<String,Map<String,List<MessageBean>>>  allUserRMap=new  ConcurrentHashMap<String,Map<String,List<MessageBean>>>();
	
//	/**
//	 *存储所有用户   ---------------已经看过的消息
//	 */
//	public static final Map<String,List<MessageBean>>  allUserVMap=new  ConcurrentHashMap<String,List<MessageBean>>();
	
	
	/**
	 * 将string转化为html格式字符StringEscapeUtils这个工具类不能转换\n -> <br/>
	 * @param message
	 * @return
	 */
	private String htmlChangeWithBR(String message){
		return changToBR(StringEscapeUtils.escapeHtml(message));
	}
	/**
	 * 将string中\n转化为<br/>
	 * @param str
	 * @return
	 */
	private String changToBR(String str){
		return str.replaceAll("\n", "<br/>");
	}
	
	/**
	 * 获得当前string类型的格式化后的日期
	 * @return
	 */
	private String getNowStringDate(){
		return getStringDate(new Date());
	}
	
	/**
	 * 获得格式化的日期
	 * @param date
	 * @return
	 */
	private String getStringDate(Date date){
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.format(date);
	}
 /**
  * JSON对象测试  将javaBean对象转换为json字符串测试
  * @param args
  */
	public static void main(String args[]) {
		ArrayList<MessageBean> messageList = new ArrayList<MessageBean>();
		for (int i = 0; i < 10; i++) {
			MessageBean bean = new MessageBean();
			bean.setTime("时间"+i);
			bean.setMessage("信息"+i);
			messageList.add(bean);
		}
		Map<String,List<MessageBean>> messageMap=new HashMap<String,List<MessageBean>>();
		messageMap.put("用户飞：", messageList);
		MessageListBean messageListBean=new MessageListBean();
		messageListBean.setMessageMap(messageMap);
//		messageListBean.setMessageList(messageList);
//		messageListBean.setAuthorName("licg1234");
		JSONObject A = JSONObject.fromObject(messageListBean);
		System.out.println(A.toString());
		allUserList.add("111");
		allUserList.add("222");
		allUserList.add("11331");
		JSONArray allUserListJson = JSONArray.fromObject(allUserList);
		System.out.println(allUserListJson.toString());
	}
	
	
}
